<template>
  <el-card>
    <el-form ref="addForm" label-width="100px" :model="goodsData" :rules="rules">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基本信息" name="first">
          <el-form-item label="一级分类" prop="first_cateid">
            <el-select v-model="goodsData.first_cateid" placeholder="请选择" @change="firstCateChange">
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :value="item.id"
                :label="item.catename"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类" prop="second_cateid">
            <el-select v-model="goodsData.second_cateid" placeholder="请选择">
              <el-option
                v-for="item in secondCateList"
                :key="item.id"
                :label="item.catename"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称" prop="goodsname">
            <el-input v-model="goodsData.goodsname" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input v-model="goodsData.price" placeholder="请输入商品价格"></el-input>
          </el-form-item>
          <el-form-item label="市场价格" prop="market_price">
            <el-input v-model="goodsData.market_price" placeholder="请输入市场价格"></el-input>
          </el-form-item>

          <el-form-item label="商品图片" prop="img">
            <el-upload
              action="#"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :auto-upload="false"
              :limit="1"
              :on-exceed="limitTips"
              :on-change="fileChange"
              :file-list="imgList"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
          </el-form-item>

          <el-form-item label="商品规格" prop="specsid">
            <el-select v-model="goodsData.specsid" placeholder="请选择" @change="specsChange">
              <el-option
                v-for="item in specsList"
                :key="item.id"
                :label="item.specsname"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="规格属性值" prop="sepcsarr">
            <el-select v-model="goodsData.specsattr" placeholder="请选择" multiple>
              <el-option
                v-for="(item,index) in specsAttrs"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="是否新品" prop="isnew">
            <el-radio-group v-model="goodsData.isnew">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否热卖" prop="ishot">
            <el-radio-group v-model="goodsData.ishot">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="goodsData.status">
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="详细描述" name="second">
          <el-form-item prop="description" label-width="0">
            <vueWangeditor
              v-model="goodsData.description"
              ref="description"
              id="description"
              width="100%"
              style="height:500px"
            ></vueWangeditor>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
      <el-form-item label-width="0">
        <el-button type="primary" @click="submitForm">立即提交</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import vueWangeditor from "vue-wangeditor";
import { getCateList } from "../../request/category";
import { getSpecsList } from "../../request/specs";
import { getGoodsById } from "../../request/goods";
export default {
  components: {
    vueWangeditor
  },
  data() {
    // 自定义表单元素校验规则
    const descValidate = (rule, value, callback) => {
      const desc = this.$refs.description.getHtml();
      if (desc === "<p><br></p>") {
        //  return this.$error('请输入商品描述');
        return callback(new Error("请输入商品描述"));
      }
      callback();
    };
    return {
      // 上传组件相关属性
      dialogImageUrl: "",
      dialogVisible: false,
      // 默认显示的标签页
      activeName: "first",
      // 分类数组
      cateList: [],
      // 二级分类数组
      secondCateList: [],

      // 规格数组
      specsList: [],
      // 规格可选值数组
      specsAttrs: [],
      // 商品图片
      imgList: [],
      goodsData: {
        first_cateid: "", // 一级分类id
        second_cateid: "", // 二级分类id
        goodsname: "", // 商品名称
        market_price: "", // 市场价格
        price: "", // 零售价格
        img: "", // 商品图片
        description: "", // 商品详情
        specsid: "", // 规格id
        specsattr: "", // 规格属性值
        isnew: "", // 是否新品
        ishot: "", // 是否热卖
        status: "" // 状态
      },
      // 表单校验规则
      rules: {
        first_cateid: { required: true, message: "请选择" },
        second_cateid: { required: true, message: "请选择" },
        goodsname: { required: true, message: "请输入" },
        market_price: { required: true, message: "请输入" },
        price: { required: true, message: "请输入" },
        // img: {}, // 商品图片
        description: { validator: descValidate, trigger: "blur" }, // 商品详情
        specsid: { required: true, message: "请选择" },
        specsattr: { required: true, message: "请选择" },
        isnew: { required: true, message: "请选择" },
        ishot: { required: true, message: "请选择" },
        status: { required: true, message: "请选择" }
      }
    };
  },
  methods: {
    // 提交表单
    submitForm() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          // {}=>FormData
          const fd = new FormData();
          for (let key in this.goodsData) {
            fd.append(key, this.goodsData[key]);
          }
          // 将富文本编辑器的内容追加到fd对象中
          fd.append("description", this.$refs.description.getHtml());
          fd.append("id", this.$route.params.id);
          const res = await this.$http.post("/api/goodsedit", fd);
          if (res.code === 200) {
            this.$success(res.msg);
            return this.$router.push("/goods");
          }
          this.$error(res.msg);
        }
      });
    },
    // 监听图片的改变
    fileChange(file) {
      // 将图片的原始信息赋值给img
      this.goodsData.img = file.raw;
    },
    limitTips() {
      this.$error("此处最多上传1张图片");
    },
    // 图片上传相关方法
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 监听规格的改变
    specsChange(id, flag = true) {
      // 通过id查找索引
      const index = this.specsList.findIndex(item => item.id === id);
      this.specsAttrs = this.specsList[index].attrs;
      // 鼠标点击规格下拉列表的时候:清空一下规格属性值
      if (flag) {
        this.goodsData.specsattr = [];
      }
    },
    // 监听一级分类的改变
    firstCateChange(id) {
      // 通过id查找索引
      const index = this.cateList.findIndex(item => item.id === id);
      // 更新二级分类数组
      this.secondCateList = this.cateList[index].children;
    },
    // 切换tabs标签页
    handleClick(tab, event) {
      console.log(tab, event);
    },
    // 获取默认数据
    async dataInit() {
      const [cateList, specsList, goodsData] = await this.$http.all([
        getCateList(),
        getSpecsList(),
        getGoodsById(this.goodsData.id)
      ]);
      // 分类列表
      this.cateList = cateList;
      // 规格列表
      this.specsList = specsList;
      // 被编辑的商品信息
      this.goodsData = goodsData;
      // 更新商品图片数组
      this.imgList =
        goodsData.img === "" ? [] : [{ url: this.$imgBaseURL + goodsData.img }];
      // 手动触发一级分类change事件回调函数
      this.firstCateChange(goodsData.first_cateid);
      // 手动触发规格下拉框的change事件回调函数
      this.specsChange(goodsData.specsid, false);
      this.goodsData.specsattr = goodsData.specsattr.split(",");
      //  手动设置富文本编辑器的内容
      this.$refs.description.setHtml(goodsData.description);
    }
  },
  created() {
    // 获取商品id
    this.goodsData.id = this.$route.params.id;
    // 数据初始化
    this.dataInit();
  }
};
</script>

<style lang="less" scoped>
.el-input {
  width: 400px;
}
</style>